import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lottie/lottie.dart';
import 'package:squat_easy/generated/assets.dart';
import 'package:squat_easy/se_voice_record/se_voice_record.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

class SeRecordOverlay extends StatefulWidget {
  const SeRecordOverlay({super.key, required this.onCompleted, this.onClose});

  final VoidCallback? onClose;
  final Function(int fileDuration, String path, String fileName, int fileSize)? onCompleted;

  @override
  State<SeRecordOverlay> createState() => _SeRecordOverlayState();
}

class _SeRecordOverlayState extends State<SeRecordOverlay> {
  Timer? _timer;
  late SeVoiceRecord _record;
  String? _path;
  String? _fileName;
  int _voiceDuration = 0;
  int _fileSize = 0;

  bool isCancel = false;
  bool isRecording = false;

  @override
  void initState() {
    super.initState();
  }

  void callback(int voiceDuration, String path, String fileName, int fileSize) {
    _voiceDuration = voiceDuration;
    _path = path;
    _fileSize = fileSize;
    _fileName = fileName;
  }

  @override
  void dispose() {
    if (null != _timer) {
      _timer?.cancel();
      _timer = null;
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: const Color(0xFF000000).withOpacity(0.6),
      child: _bottomBg().alignBottom(),
    );
  }

  ///取消录音动画
  Widget _selectedCancelAreaAnimationView() => _buildSelectedAreaAnimationView(
        Colors.white,
      );

  ///长按录音动画
  Widget _selectedPressAreaAnimationView() => _buildSelectedAreaAnimationView(
        Colors.white,
      );

  final recordingViewHeight = 90.w;
  final recordingViewWidth = 160.w;

  Widget _buildSelectedAreaAnimationView(Color color) {
    return Container(
      alignment: Alignment.center,
      child: Container(
        width: recordingViewWidth,
        height: recordingViewHeight,
        padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 40.w),
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(6), color: color),
        child: Lottie.asset(
          'assets/json/voice_record.json',
          width: 80.w,
          height: 35.w,
          fit: BoxFit.contain,
        ),
      ),
    );
  }

  Widget _buildText() => TextWidget.oneLine(
        text: isCancel ? 'Release Cancel' : (isRecording ? 'Release Send' : ''),
        fontSize: 16,
        color: Colors.white,
      );

  ///底部扇形背景
  Widget _bottomBg() => FractionallySizedBox(
        widthFactor: 1,
        child: Stack(
          alignment: Alignment.bottomCenter,
          children: [
            Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                _buildText().paddingBottom(28.w),
                Image.asset(
                  Assets.webpIcVoiceRecordBg1,
                  height: 250.w,
                  fit: BoxFit.fill,
                  color: Colors.white,
                ),
              ],
            ),
            _speakerIcon(),
            _buildCloseBtn().positioned(right: 50.w, bottom: 200.w),
          ],
        ),
      );

  void _callback() {
    if (_voiceDuration > 0 && null != _path) {
      widget.onCompleted?.call(_voiceDuration, _path!, _fileName ?? '', _fileSize);
    }
  }

  ///录音图标
  Widget _speakerIcon() => SizedBox(
        height: 250.w,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            isCancel
                ? _selectedCancelAreaAnimationView()
                : (isRecording ? _selectedPressAreaAnimationView() : SizedBox(height: recordingViewHeight)),
            GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTapDown: (details) {},
              onLongPressStart: (details) {
                setState(() {
                  _record = SeVoiceRecord(callback);
                  _record.start();
                  isRecording = true;
                });
              },
              onLongPressEnd: (details) async {
                await _record.stop();

                setState(() {
                  if (!isCancel) _callback();
                  isCancel = false;
                  isRecording = false;
                });
              },
              onLongPressMoveUpdate: (details) {
                Offset global = details.globalPosition;
                setState(() {
                  bool cancel = global.dy < ScreenUtil().screenHeight - 250.w;
                  isCancel = cancel;
                });
              },
              child: Image.asset(
                isRecording ? Assets.pngAudioSelect : Assets.pngAudioNormal,
                width: 80.w,
                height: 80.w,
              ),
            ).paddingBottom(20.w),
          ],
        ),
      );

  Widget _buildCloseBtn() {
    return ButtonWidget.icon(
      Image.asset(
        Assets.pngAudioClose,
        width: 44.w,
        height: 44.w,
      ),
      onTap: () => widget.onClose?.call(),
      hasInkWell: false,
    );
  }
}
